package com.zzh.test1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class SpinLockDemo {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "\t --------come in");
        // 自旋锁 只有null才能获取锁
        while (!atomicReference.compareAndSet(null, thread)) {//如果原来的值为null，则将当前线程设置为原子引用的值，并返回true，否则一直循环等待，直到原子引用的值被设置为null
            System.out.println(Thread.currentThread().getName() + "\t --------wait for lock.........");
        }
    }

    public void unLock() {
        Thread thread = Thread.currentThread();
        // 释放锁 原子引用的值只能是当前线程才能释放锁
        atomicReference.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "\t --------task over,unLock.........");
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(() -> {
            spinLockDemo.lock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.unLock();
        }, "A").start();


        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            spinLockDemo.lock();
            spinLockDemo.unLock();
        }, "B").start();
    }

}
